package gui5e_modules;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import gui5e.*;


public class Preferences {

	// fields
	public static SourceFolder folder;
	public WatchFS watcher;
	public File chosenFile;
	public  Map<String, String> chosen= new HashMap<String, String>();
	
	//private Thread thread; -> not necessary because stop and restart via watcher!!
	
	//constructors
	private Preferences(SourceFolder folder_, WatchFS watcher_){
		folder = folder_;
		watcher = watcher_;
	}
	
	//factory method
	public static Preferences create(ModPreferences parent, String foldername_){	
		try{
			SourceFolder folder_ = SourceFolder.createFolder(foldername_);
			Thread thread_ = new Thread();
			WatchFS  watcher_ = new WatchFS(parent, folder_.folder);
			thread_ = new Thread(watcher_);
			thread_.start();
			return new Preferences(folder_, watcher_);
		}catch (Exception e){	//Catch exception if any
			System.err.println("Error: " + e.getMessage());
			return null;  
		}
	}
	
	//choose file method

	public void chose(int f_){
	  	File[] files_ =  watcher.files;
		Arrays.sort(files_);
		chosenFile = files_[f_];
		try {
			List<String> lines = Files.readAllLines(chosenFile.toPath(), Charset.defaultCharset());
			for(String line : lines){
                String[] values = line.split(": ");  
                String ID = values[0];  
                String name = values[1];  
                chosen.put(ID, name); 
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// get value method
	public String get(String key_){
		String value = chosen.get(key_);
		return value;
	}
	
	// get value method
	public int getInt(String key_){
		int value = Integer.parseInt(chosen.get(key_));
		return value;
	}
	// get value method
	public String[] getArray(String key_){
		String value = chosen.get(key_);
		String[] values = value.split(",");
		return values;
	}
	
	// get value method
	public int[] getIntArray(String key_){
		String value = chosen.get(key_);
		String[] values = value.split(",");
		int[] vals = new int[values.length];
		for(int i = 0; i < values.length; i++){
			vals[i] = Integer.parseInt(values[i]);
		}
		return vals;
	}
}
